﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;

namespace System.Serialization
{
    /// <summary>
    /// 序列化扩展
    /// </summary>
    public static partial class SerializationManager
    {
        #region Bson序列化

        /// <summary>
        /// Bson二进制序列化
        /// </summary>
        /// <param name="data">要序列化的对象</param>
        /// <returns>byte[]</returns>
        public static byte[] BsonSerialize(this object data)
        {
            using (var stream = new MemoryStream())
            {
                var bsonWriter = new BsonWriter(stream);
                var serializer = new JsonSerializer();
                serializer.Serialize(bsonWriter, data);
                return stream.GetBuffer();
            }
        }

        /// <summary>
        /// Bson反序列化二进制对象
        /// </summary>
        /// <typeparam name="T">要Bson反序列成的类型</typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static T BsonDeSerialize<T>(this byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
                var reader = new BsonReader(stream);
                if (typeof (ICollection).IsAssignableFrom(typeof (T)))
                {
                    reader.ReadRootValueAsArray = true;
                }
                var serializer = Newtonsoft.Json.JsonSerializer.Create(null);
                return serializer.Deserialize<T>(reader);
            }
        }
        /// <summary>
        /// Bson反序列化Stream
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static T BsonDeSerialize<T>(this Stream stream)
        {
            using (var reader = new BsonReader(stream))
            {
                if (typeof (ICollection).IsAssignableFrom(typeof (T)))
                {
                    reader.ReadRootValueAsArray = true;
                }
                var serializer = Newtonsoft.Json.JsonSerializer.Create(null);
                return serializer.Deserialize<T>(reader);
            }
        }

        #endregion
    }
}
